package com.health.viewscontrols.medical.device.bp;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.health.httpbean.model.BpModel;
import com.health.tablebean.BTDevice;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.BlueToothConstant;

import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 脉搏波血压计4.0
 */
public class BPMbb4Activity extends BaseDeviceActivity {

    Timer timer;
    TimerTask task;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            connDevice();
        }
    };

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bp_mbb4);
        mBleDevice.setDevice_Service_UUID(BlueToothConstant.MAIBOBO_UUID_SERVICE);
        mBleDevice.setDevice_Notify_UUID(BlueToothConstant.MAIBOBO_UUID_NOTIFY);
        mBleDevice.setDEVICE_write_UUID(BlueToothConstant.MAIBOBO_UUID_WRITE);
        mBleDevice.setConnectChangedListener(new OnDeviceConnectChangedListener() {
            @Override
            public void onConnected() {
                Log.e(TAG, "onConnected: ");
                isConnected = true;
                runOnUiThread(() -> {
                    if (timer != null) {
                        timer.cancel();
                    }
                    blueToothState.setText("蓝牙已连接");
                    showProgressDialog("等待接收脉搏波血压计数据");
                    new Handler().postDelayed(() -> write(BlueToothConstant.CONN_DEVICE_COMMAND), 1200);
                });
            }

            @Override
            public void onDisconnected() {
                isConnected = false;
                Log.e(TAG, "onDisconnected: ");
                cancelProgressDialog();
                runOnUiThread(() -> {
                    blueToothState.setText("蓝牙连接失败");
                });
            }
        });

        startDevice();
    }

    private void connDevice() {
        if (isConnected) {
            blueToothState.setText("蓝牙已连接");
            showProgressDialog("等待接收脉搏波血压计数据");
            new Handler().postDelayed(() -> write(BlueToothConstant.CONN_DEVICE_COMMAND), 1200);
        } else {
            showProgressDialog("正在连接脉搏波4.0设备");
            blueToothState.setText("蓝牙开始连接");
            Log.e(TAG, "startDevice: " + deviceEnum.getMac());
            mBleDevice.setConnect(true);
            mBleDevice.setMAC(deviceEnum.getMac());
            mBleDevice.connect(deviceEnum.getMac());
        }
    }

    @Override
    public void startDevice() {
        connDevice();
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
            }
        };
        timer.schedule(task,6000);
    }

    @Override
    public void update(String hexString) {
        try {
            if ("aa80020301010001".equals(hexString)) {
                write(BlueToothConstant.START_DEVIC_COMMANDE);
                Log.e(TAG, "血压计返回连接指令: " + hexString);
            }else if("cc80020301010001".equals(hexString)) {
                write(BlueToothConstant.START_DEVIC_COMMANDE);
            } else if ("aa80020301020002".equals(hexString)) {
                Log.e(TAG, "血压计返回启动测量指令: " + hexString);
            } else if ("aa80020301030003".equals(hexString)) {
                //血压计返回停止测量结果 断开连接
                disconnectDevice();
                Log.e(TAG, "血压计返回停止测量结果: 蓝牙主动断开连接");
            } else {
                String command = hexString.substring(10, 12);
                if ("06".equals(command)) {
                    int bloodUp = Integer.parseInt(hexString.substring(26, 30), 16);
                    int bloodDown = Integer.parseInt(hexString.substring(30, 34), 16);
                    int heart = Integer.parseInt(hexString.substring(34, 38), 16);
                    Log.e(TAG, "高压: " + bloodUp + "  低压：" + bloodDown + "  心率：" + heart);
                    saveMaiboboData(bloodUp, bloodDown, heart);
                    //write(BlueToothConstant.CLOSE_DEVICE_COMMAND);
                } else if ("05".equals(command)) {
                    int realBloodPressure = Integer.parseInt(hexString.substring(20, 22), 16);
                    tv_result.setText("实时数据: " + realBloodPressure + " /mmHg");
                } else if ("07".equals(command)) {
                    ToastUtils.showShort("测量错误,重新测量");
                    disconnectDevice();
                    tv_state.setText("测量错误,重新测量");
                } else {
                    Log.e(TAG, "notify: " + hexString);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveMaiboboData(int bloodUp, int bloodDown, int heart) {
        try {
//            disconnectDevice();
            cancelProgressDialog();
            //收缩压、舒张压、心率
            String results = DeviceShowSaveData.getDataShow(bloodUp + ";" + bloodDown + ";" + heart + ";",
                    BluetoothConstant.XUEYA_YE680A_YUYUE);

            BpModel bpModel = new BpModel();
            bpModel.setHighpressure(bloodUp + "");
            bpModel.setLowvoltage(bloodDown + "");
            bpModel.setPulse(heart + "");
            DeviceShowSaveData.saveXueya(GsonUtils.toJson(bpModel));

            tv_result.setText("测量结果：\n        " + results);
            tv_state.setText("获取测量结果成功");
        } catch (Exception e) {
            Log.e(TAG, "报异常了: " + e.toString());
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.e(TAG, "disconnectDevice: " );
        try {
            mBleDevice.setConnect(false);
            mBleDevice.disconnect();
            mBleDevice.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

}
